package top.haijunit.work.modules.repo.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import top.haijunit.work.core.doamin.ExceptionServer;
import top.haijunit.work.core.doamin.PageQuery;
import top.haijunit.work.core.doamin.ResultPage;
import top.haijunit.work.converter.RepoConverter;
import top.haijunit.work.modules.repo.domain.DeptInfo;
import top.haijunit.work.modules.repo.entity.DepartmentEntity;
import top.haijunit.work.modules.repo.mapper.DepartmentMapper;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author zhanghaijun
 * @description 针对表【repo_department(部门表)】的数据库操作Service
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DepartmentService extends ServiceImpl<DepartmentMapper, DepartmentEntity> {

    private final RepoConverter converter;

    private Wrapper<DepartmentEntity> queryConditional(DeptInfo deptInfo) {
        LambdaQueryWrapper<DepartmentEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (null != deptInfo) {
            queryWrapper.like(CharSequenceUtil.isNotBlank(deptInfo.getDeptName()), DepartmentEntity::getDeptName, deptInfo.getDeptName());
            queryWrapper.like(CharSequenceUtil.isNotBlank(deptInfo.getNickname()), DepartmentEntity::getNickname, deptInfo.getNickname());
            queryWrapper.eq(Objects.nonNull(deptInfo.getParentCode()), DepartmentEntity::getParentCode, deptInfo.getParentCode());
            queryWrapper.eq(null != deptInfo.getStatusCode(), DepartmentEntity::getStatusCode, deptInfo.getStatusCode());
        }
        queryWrapper.orderByAsc(DepartmentEntity::getDeptLevel);
        return queryWrapper;
    }

    private void checkChange(DeptInfo dto) {
        Assert.hasLength(dto.getDeptName(), "部门名称不能为空！");
        Assert.hasLength(dto.getNickname(), "部门简称不能为空！");
        Assert.notNull(dto.getParentCode(), "上级部门不能为空！");
        LambdaQueryWrapper<DepartmentEntity> query = new LambdaQueryWrapper<>();
        if (Objects.nonNull(dto.getDeptCode())) {
            query.eq(DepartmentEntity::getDeptName, dto.getDeptName());
            query.or().eq(DepartmentEntity::getNickname, dto.getNickname());
        } else {
            query.ne(DepartmentEntity::getUniqCode, dto.getDeptName());
            query.and(wrapper -> wrapper.eq(DepartmentEntity::getDeptName, dto.getDeptName()).or().eq(DepartmentEntity::getNickname, dto.getNickname()));
        }
        if (this.exists(query)) {
            throw new ExceptionServer("部门名称已存在！");
        }
        if (!Objects.equals(0L, dto.getParentCode()) && !this.exists(new LambdaQueryWrapper<DepartmentEntity>().eq(DepartmentEntity::getUniqCode, dto.getParentCode()))) {
            throw new ExceptionServer("上级部门不存在！");
        }
    }

    /**
     * 获取数据分页
     */
    public ResultPage<DeptInfo> selectPageList(PageQuery pageQuery, DeptInfo deptInfo) {
        Page<DepartmentEntity> entityPage = this.baseMapper.selectPage(pageQuery.build(), queryConditional(deptInfo));
        return ResultPage.build(entityPage, converter::convertDept);
    }

    /**
     * 获取数据列表
     */
    public Collection<DeptInfo> selectList(DeptInfo deptInfo) {
        List<DepartmentEntity> entityList = this.baseMapper.selectList(queryConditional(deptInfo));
        return converter.convertDept(entityList);
    }

    /**
     * 获取数据详情
     */
    public DeptInfo selectDetail(Long code) {
        LambdaQueryWrapper<DepartmentEntity> query = new LambdaQueryWrapper<>();
        query.eq(DepartmentEntity::getUniqCode, code);
        List<DepartmentEntity> entityList = this.baseMapper.selectList(query);
        if (CollUtil.isEmpty(entityList)) {
            throw new ExceptionServer("数据不存在");
        }
        if (entityList.size() > 1) {
            log.error("数据库数据异常，存在重复的异常数据: {} 重复", code);
        }
        return converter.convert(CollUtil.getFirst(entityList));
    }

    /**
     * 添加数据
     */
    public Long insert(DeptInfo dto) {
        checkChange(dto);
        DepartmentEntity entity = converter.convert(dto);
        this.baseMapper.insert(entity);
        return entity.getUniqCode();
    }

    /**
     * 修改数据
     */
    public Long modify(DeptInfo dto) {
        checkChange(dto);
        DepartmentEntity entity = converter.convert(dto);
        Assert.notNull(entity.getUniqCode(), "修改的数据不存在");
        LambdaQueryWrapper<DepartmentEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DepartmentEntity::getUniqCode, entity.getUniqCode());
        this.baseMapper.update(entity, wrapper);
        return entity.getUniqCode();
    }

    /**
     * 删除数据
     */
    public Long delete(Long code) {
        LambdaQueryWrapper<DepartmentEntity> query = new LambdaQueryWrapper<>();
        query.eq(DepartmentEntity::getUniqCode, code);
        this.baseMapper.delete(query);
        return code;
    }
}
